package cn.edu.hzw.criminalintent.fragmnet

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.text.format.DateFormat
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import cn.edu.hzw.criminalintent.R
import cn.edu.hzw.criminalintent.bean.Crime
import cn.edu.hzw.criminalintent.databinding.FragmentCrimeBinding
import cn.edu.hzw.criminalintent.model.CrimeDetailViewModel
import cn.edu.hzw.criminalintent.utils.PictureUtils
import cn.edu.hzw.criminalintent.utils.PictureUtils.getScaledBitmap
import java.io.File
import java.util.*

private const val ARG_CRIME_ID = "crime_id"
private const val TAG = "CrimeFragment"
private const val DIALOG_DATE = "DialogDate"
private const val REQUEST_DATE = 0
private const val REQUEST_CONTACT = 1
private const val REQUEST_PHOTO = 2
private const val DATE_FORMAT = "EEE,MMM,dd"
class CrimeFragment : Fragment(),DatePickerFragment.Callbacks {
    private lateinit var crime: Crime
    private lateinit var photoFile:File
    private lateinit var photoUri: Uri
    private var imgPhotoWidth:Int = 0
    private var imgPhotoHeight:Int = 0
    private lateinit var binding:FragmentCrimeBinding
    private val crimeDetailViewModel:CrimeDetailViewModel by lazy {
        ViewModelProvider(this).get(CrimeDetailViewModel::class.java)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        crime = Crime()
        val crimeId:UUID =
            arguments?.getSerializable(ARG_CRIME_ID) as UUID
//        Log.d(TAG, "args bundle crime ID:$crimeId")
        crimeDetailViewModel.loadCrime(crimeId)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentCrimeBinding.inflate(layoutInflater,container,false)
        return binding.root
//        binding.btnCrimeDate.apply {
//            /**
//             * 文本更换为当前时间
//             */
//            text = crime.date.toString()
//            /**
//             * 禁用button按钮，确保它不会响应用户点击
//             */
//            isEnabled = false
//        }
    }

    /**
     * 观察数据变化
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        crimeDetailViewModel.crimeLiveData.observe(
            viewLifecycleOwner,
            androidx.lifecycle.Observer { crime ->
                crime?.let {
                    this.crime = crime
                    /**
                     * 获取照片文件位置
                     */
                    photoFile = crimeDetailViewModel.getPhotoFile(crime)
                    /**
                     * 添加图片URI属性
                     */
                    photoUri = FileProvider.getUriForFile(requireActivity(),
                    "cn.edu.hzw.criminalintent.fileprovider",photoFile)
                    updateUI()
                }
            })
        binding.btnCrimeDate.setOnClickListener {
            /**
             * 添加对newInstance（）的调用
             */
            DatePickerFragment.newInstance(crime.date).apply {
                setTargetFragment(this@CrimeFragment, REQUEST_DATE)
                show(this@CrimeFragment.parentFragmentManager, DIALOG_DATE)
            }
        }
    }

    private fun updateUI() {
        binding.etCrimeTitle.setText(crime.title)
        binding.btnCrimeDate.text = crime.date.toString()
        binding.cbCrimeSolved.apply {
            isChecked = crime.isSolved
            jumpDrawablesToCurrentState()
        }
        if (crime.suspect.isNotEmpty()){
            binding.crimeSuspect.text = crime.suspect
        }
        updatePhotoView(imgPhotoWidth,imgPhotoHeight)
    }

    private fun updatePhotoView(width:Int,height:Int){
        if (photoFile.exists()){
            val bitmap = getScaledBitmap(photoFile.path,width,height)
            binding.crimePhoto.setImageBitmap(bitmap)
            binding.crimePhoto.contentDescription = getString(R.string.crime_photo_image_description)
        }else{
            binding.crimePhoto.setImageDrawable(null)
            binding.crimePhoto.contentDescription = getString(R.string.crime_photo_no_image_description)
        }
    }

    val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                val contactUri: Uri = it.data?.data!!
                val queryFilds = arrayOf(ContactsContract.Contacts.DISPLAY_NAME)
                val cursor = requireActivity().contentResolver.query(
                    contactUri, queryFilds, null,
                    null, null
                )
                cursor.use {
                    if (it?.count == 0) {
                        return@use
                    }
                    it?.moveToFirst()
                    val suspect = it?.getString(0)
                    crime.suspect = suspect!!
                    crimeDetailViewModel.saveCrime(crime)
                    binding.crimeSuspect.text = suspect
                }
            }
        }

    private val startForResult2 =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                updatePhotoView(imgPhotoWidth, imgPhotoHeight)
            }
        }

    private fun getCrimeReport():String{
        val solvedString = if (crime.isSolved){
            getString(R.string.crime_report_solved)
        }else{
            getString(R.string.crime_report_unsolved)
        }
        val dateString = DateFormat.format(DATE_FORMAT,crime.date).toString()
        var suspect = if (crime.suspect.isBlank()){
            getString(R.string.crime_report_no_suspect)
        }else{
            getString(R.string.crime_report_suspect,crime.suspect)
        }
        return String.format(
            resources.getString(R.string.crime_report),
            crime.title,
            dateString,
            solvedString,
            suspect
        )
    }

    override fun onStart() {
        super.onStart()
        //监听器
        val titleWatcher = object :TextWatcher{
            override fun beforeTextChanged(sequence: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(sequence: CharSequence?, start: Int, count: Int, after: Int) {
               crime.title = sequence.toString()
            }

            override fun afterTextChanged(sequence : Editable?) {

            }
        }

        binding.etCrimeTitle.addTextChangedListener(titleWatcher)
        /**
         * 更新checkbox状态
         */
        binding.cbCrimeSolved.apply {
            setOnCheckedChangeListener { _, isChecked ->
                crime.isSolved = isChecked
                jumpDrawablesToCurrentState()
            }
        }
        /**
         * 发送短信
         */
        binding.crimeReport.setOnClickListener {
            Intent(Intent.ACTION_SEND).apply {
                type = "text/plain"
                putExtra(Intent.EXTRA_TEXT,getCrimeReport())
                putExtra(Intent.EXTRA_SUBJECT,getString(R.string.crime_report_subject))
            }.also { intent->
                val chooserIntent = Intent.createChooser(intent,getString(R.string.send_report))
                startActivity(chooserIntent)
            }
        }
        /**
         * 选择联系人
         */
        binding.crimeSuspect.apply {
            val pickContactIntent = Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI)
            setOnClickListener {
                startForResult.launch(pickContactIntent)
            }
            /**
             * 检查是否存在联系人应用
             */
//            pickContactIntent.addCategory(Intent.CATEGORY_HOME)
            val packageManager:PackageManager = requireActivity().packageManager
            val resolvedActivity: ResolveInfo? =
                packageManager.resolveActivity(pickContactIntent,
                PackageManager.MATCH_DEFAULT_ONLY)
            if (resolvedActivity == null){
                isEnabled = false
            }
        }
        /**
         * 给嫌疑人打电话
         */
        binding.callSuspect.setOnClickListener{

        }
        /**
         * 使用相机intent
         */
        binding.crimeCamera.apply {
            val packageManager:PackageManager = requireActivity().packageManager
            val captureImage = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            val resolveActivity:ResolveInfo?=packageManager.resolveActivity(captureImage,
                PackageManager.MATCH_DEFAULT_ONLY)
            if (resolveActivity == null){
                isEnabled = false
            }
            setOnClickListener {
                captureImage.putExtra(MediaStore.EXTRA_OUTPUT,photoUri)
                val cameraActivities:List<ResolveInfo> =
                    packageManager.queryIntentActivities(captureImage,
                    PackageManager.MATCH_DEFAULT_ONLY)
                for(cameraActivity in cameraActivities){
                    requireActivity().grantUriPermission(
                        cameraActivity.activityInfo.packageName,
                        photoUri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    )
                }
                startForResult2.launch(captureImage)
            }
        }
        /**
         * 缩略图放大
         */
        binding.crimePhoto.viewTreeObserver.addOnGlobalLayoutListener {
            imgPhotoWidth = binding.crimePhoto.measuredWidth
            imgPhotoHeight = binding.crimePhoto.measuredHeight
        }

        // 缩略图放大功能
        binding.crimePhoto.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("img_path",photoFile.path)
            PhotoPreviewDialogFragment().newInstance(bundle).show(this@CrimeFragment.parentFragmentManager, "PreviewPhotoDialog")
        }
    }

    override fun onStop() {
        super.onStop()
        crimeDetailViewModel.saveCrime(crime)
    }

    override fun onDetach() {
        super.onDetach()
        requireActivity().revokeUriPermission(photoUri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    }

    /**
     * 实现回调接口
     */
    override fun onDateSelected(date: Date) {
        crime.date = date
        updateUI()
    }

    companion object{
        fun newInstance(crimeId:UUID):CrimeFragment{
            val args = Bundle().apply {
                putSerializable(ARG_CRIME_ID,crimeId)
            }
            return CrimeFragment().apply {
                arguments = args
            }
        }
    }
}